<template>
  <!-- line-gap:列宽 -->
  <waterfall class="goods-wrapper" :line-gap="colWidth" :watch="goods">
    <!-- each component is wrapped by a waterfall slot -->
    <waterfall-slot
      v-for="(item, index) in goods"
      :width="item.width"
      :height="item.height"
      :order="index"
      :key="item.id"
    >
      <!-- 图片高度根据父容器高度自适应: -->
      <!-- 图片高度=父容器高度-2行文字高度 -->
      <img :src="item.img" :height="item.height-70" />
      <p class="good-desc">
        <span class="is-direct" v-if="item.isDirect">直营</span>
        <span class="is-have" v-if="item.isHave">缺货</span>
        <span>{{item.name}}</span>
      </p>
      <div class="good-price-volume">
        <p class="price">￥{{item.price}}</p>
        <p class="volume">销量:{{item.volume}}</p>
      </div>
    </waterfall-slot>
  </waterfall>
</template>

<script type="text/ecmascript-6">
import Waterfall from 'vue-waterfall/lib/waterfall'
import WaterfallSlot from 'vue-waterfall/lib/waterfall-slot'

export default {
  name: 'Goods',
  data () {
    return {
      goods: [],
      colWidth: 0
    }
  },
  created: function () {
    console.log(`屏幕宽度:${document.documentElement.clientWidth}`)
    this.initData()
  },
  methods: {
    initData: function () {
      // 计算一列的宽度
      this.colWidth = document.documentElement.clientWidth * 0.5
      // 最大高度
      const MAX_IMG_HEIGHT = 250
      // 最小高度
      const MIN_IMG_HEIGHT = 150
      this.$http.get('/main/goods')
        .then(data => {
          const list = data
          list.forEach(it => {
            it.width = document.documentElement.clientWidth * 0.5
            // Math.random() -> 0 - 1 随机数 * (高度区间) + 最低的图片高度
            it.height = Math.floor(Math.random() * (MAX_IMG_HEIGHT - MIN_IMG_HEIGHT) + MIN_IMG_HEIGHT)
          })
          this.goods = list
          console.log(this.goods)
        })
        .catch(err => {
          console.log(err)
        })
    }
  },
  components: {
    Waterfall,
    WaterfallSlot
  }
}
</script>

<style lang="stylus" scoped>
.goods-wrapper
  font-size: px2rem(30)
  line-height :px2rem(40)
  width: 100%
  >>> .vue-waterfall-slot
    background:$color-white
    img
      width:96%
    .good-desc
      text-align :left
      overflow: hidden
      text-overflow: ellipsis
      word-break: break-word
      -webkit-line-clamp: 2
      -webkit-box-orient: vertical
      display: -webkit-box
      margin: px2rem(8)
      .is-direct
        padding:px2rem(10)
        color:$color-red
      .is-have
        padding:px2rem(10)
    .good-price-volume
      display: flex
      justify-content :space-between
      padding:px2rem(10)
      .price
        color: $color-red
</style>
